package com.example.send.util.kdxf;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class KDXF {

//    private static final String WEBOCR_URL = "http://webapi.xfyun.cn/v1/service/v1/ocr/general";
    private static final String WEBOCR_URL = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting";
    // 应用ID (必须为webapi类型应用，并印刷文字识别服务，参考帖子如何创建一个webapi应用：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
    private static final String APPID = "f40576ee";
    // 接口密钥(webapi类型应用开通印刷文字识别服务后，控制台--我的应用---印刷文字识别---服务的apikey)
    private static final String API_KEY = "e215e7d1e7564bb4fc30c777f4edac6e";
    // 是否返回位置信息
    private static final String LOCATION = "false";
    // 语种(可选值：en（英文），cn|en（中文或中英混合)
    private static final String LANGUAGE = "cn|en";
    // 图片地址,图片最短边至少15px，最长边最大4096px，格式jpg、png、bmp
    private static final String PIC_PATH = "E:\\back_project\\python\\hanzi\\test\\1.jpg";

    /**
     * OCR WebAPI 调用示例程序
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, InterruptedException {

        String regex = "[\\u4e00-\\u9fa5]+";
        String path = "E:\\back_project\\python\\hanzi\\49ks\\";
        File ffile = new File(path);
        File[] fs = ffile.listFiles();
        Set<String> set = new HashSet<>();
        for (File f : fs) {
//        File f = new File("E:\\back_project\\python\\hanzi\\test\\1.jpg");
            if (!f.isDirectory()) {
                System.out.println(f.getAbsolutePath());
                try {
                    Map<String, String> header = buildHttpHeader();
                    byte[] imageByteArray = FileUtil.read(f.getAbsolutePath());
                    String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
                    String result = HttpUtil.doPost1(WEBOCR_URL, header, "image=" + URLEncoder.encode(imageBase64, "UTF-8"));
                    System.out.println(result);
                    JSONObject object = JSONObject.parseObject(result).getJSONObject("data");
                    JSONArray array = object.getJSONArray("block");
                    String word = "";
                    if (array != null && array.size() > 0) {
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject in = array.getJSONObject(i);
                            JSONArray array1 = in.getJSONArray("line");
                            if (array1 != null && array1.size() > 0) {
                                for (int j = 0; j < array1.size(); j++) {
                                    JSONObject in1 = array1.getJSONObject(j);
                                    JSONArray array2 = in1.getJSONArray("word");
                                    if (array2 != null && array2.size() > 0) {
                                        for (int k = 0; k < array2.size(); k++) {
                                            JSONObject in2 = array2.getJSONObject(k);
                                            String temp = in2.getString("content");
                                            Matcher m = Pattern.compile(regex).matcher(temp);
                                            if (m.find()) {
                                                word = temp;
                                                break;
                                            }
                                        }
                                    }
                                    if (word != null && word.length() > 0) {
                                        break;
                                    }
                                }
                            }
                            if (word != null && word.length() > 0) {
                                break;
                            }
                        }
                    }
                    if (word != null && word.length() > 0) {
                        System.out.println(word);
                        if (set.contains(word)) {
                            System.out.println("出现重复：" + f.getAbsolutePath() + "-----" + word);
                            continue;
                        } else {
                            set.add(word);
                        }
                        f.renameTo(new File(path + word + ".jpg"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Thread.sleep(3000);
        }
//        Map<String, String> header = buildHttpHeader();
//        byte[] imageByteArray = FileUtil.read(PIC_PATH);
//        String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
//        String result = HttpUtil.doPost1(WEBOCR_URL, header, "image=" + URLEncoder.encode(imageBase64, "UTF-8"));
//        System.out.println("OCR WebAPI 接口调用结果：" + result);
        //  错误码链接：https://www.xfyun.cn/document/error-code (code返回错误码时必看)
    }

    /**
     * 组装http请求头
     */
    private static Map<String, String> buildHttpHeader() throws UnsupportedEncodingException {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"location\":\"" + LOCATION + "\",\"language\":\"" + LANGUAGE + "\"}";
        String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
        String checkSum = DigestUtils.md5Hex(API_KEY + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", APPID);
        return header;
    }

}
